<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/21
 * Time: 19:24
 * @link http://www.lmterp.cn
 */

namespace app\common\service\export;

use app\common\library\Tools;
use app\common\model\ProductCategory;
use app\common\model\Product as ProductModel;
use app\common\model\ProductPurchase;
use app\common\model\ProductStore;

/**
 * 导出产品
 * Class Product
 * @package app\common\service\export
 */
class Product extends BaseExport
{
    protected $prefix = 'product';

    public function getHeader()
    {
        return [
            "product.product_id" => '产品ID',
            "product.spu" => 'SPU',
            "store.sku" => 'SKU',
            "store.stock" => '现有库存',
            "product.brand" => '品牌',
            "product.model" => '型号',
            "product.unit_id" => '计量单位',
            "product.category_id" => '分类',
            "product.name_ch" => '中文名称',
            "product.name_en" => '英文名称',
            "product.describe" => '描述信息',
            "product.warehouse_id" => '仓库',
            "product.status" => '商品状态',
            "product.image_url" => '封面图',
            "product.default_purchase" => '默认采购商',
            "product.price" => '采购价格',
            "product.declare_ch" => '申报中文名',
            "product.declare_en" => '申报英文名',
            "product.declare_price" => '申报价格',
            "product.image_list" => '图片列表',
            "product.hot" => '商品热度',
            "product.remark" => '商品备注',
            "store.store_id" => '变体id',
            "store.length" => '长(mm)',
            "store.width" => '宽(mm)',
            "store.height" => '高(mm)',
            "store.weight" => '净重(g)',
            "store.package_weight" => '包装重(g)',
            "store.price" => '变体采购价格',
            "store.image_url" => '变体主图',
            "store.attr" => '属性',
            "store.color" => '颜色',
            "store.remark" => '备注',
            "purchase.pp_id" => '采购详情ID',
            "purchase.producer_id" => '供应商',
            "purchase.min_qty" => '起订数量',
            "purchase.status" => '采购状态',
            "purchase.type" => '采购类型',
            "purchase.price" => '采购单价',
            "purchase.url" => '采购链接',
            "purchase.is_default" => '是否优先采购',
            "purchase.remark" => '采购备注',
            "product.create_time" => '录入时间',
            "product.create_by" => '录入人',
        ];
    }

    public function getData($condition = [])
    {
        $twhere = $this->parseWhere($condition);
        $pwhere = $twhere['product'];
        $swhere = $twhere['store'];
        $perwhere = $twhere['purchase'];

        $tempField = $this->getField();
        $pf = $tempField['product'];
        $sf = $tempField['store'];
        $pef = $tempField['purchase'];
        $productModel = ProductModel::where($pwhere)->with([
            'stores' => function($query)use($swhere,$sf){$query->where($swhere);},
            'purchase' => function($query)use($perwhere,$pef){$query->where($perwhere)->with(['producer']);},
            "admin"   => function($query){$query->field(["id","nickname"]);},
            // "admin.orders",
            'sbrand' => function($query){$query->field("brand_id,name_ch");},
            //'category' => function($query){$query->field("cate_id,name");},
            'unit' => function($query){$query->field("unit_id,name_ch");},
            'images' => function($query){$query->field("product_id,image_url");},
        ]);
        if(!empty($swhere))
        {
            $productModel->where("product_id", "in", function($query)use($swhere)
            {
                $query->table(ProductStore::getTable())->where($swhere)->field("product_id");
            });
        }

        if(!empty($perwhere))
        {
            $productModel->where("product_id", "in", function($query)use($perwhere)
            {
                $query->table(ProductPurchase::getTable())->where($perwhere)->field("product_id");
            });
        }

        $ret = [];
        foreach($productModel->select() as $item)
        {
            $product = $item->toArray();
            $product['create_by'] = !empty($item->admin) ? $item->admin->nickname : '系统导入';
            $product['brand'] = $item->sbrand->name_ch;
            $product['category_id'] = join('>', array_column(ProductCategory::getParentAll($item->category_id), 'name'));
            $product['unit_id'] = $item->unit->name_ch;
            $product['image_list'] = join(',', array_column($item->images->toArray(), 'image_url'));
            $product = Tools::replaceArrayKey($pf, array_intersect_key($product, $pf));
            $pArray = [];
            foreach($item->stores as $dkey => $stores)
            {
                $store = $stores->toArray();
                $store['stock'] = array_sum(array_column($stores->stock->toArray(), 'stock'))?:'';
                $store = Tools::replaceArrayKey($sf, array_intersect_key($store, $sf));
                $pArray[] = ($dkey == 0 ? $product : Tools::emptyArray($product)) + $store;
            }
            foreach($item->purchase as $k => $pur)
            {
                $purchase = $pur->toArray();
                $purchase['producer_id'] = !empty($pur->producer) ? $pur->producer->name : '';
                $purchase = Tools::replaceArrayKey($pef, array_intersect_key($purchase, $pef));
                if(isset($pArray[$k]))
                {
                    $pArray[$k] += $purchase;
                }
                else
                {
                    $pArray[$k] = Tools::emptyArray($product) + Tools::emptyArray($store) + $purchase;
                }
            }
            $ret = array_merge($pArray, $ret);
        }
        $this->sortData($ret);
        return $ret;
    }
}